<template>
  <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
    <el-form-item :label="$t('updatePassword.username')">
      <span>{{ user.username }}</span>
    </el-form-item>
    <!--    <el-form-item prop="password" :label="$t('updatePassword.password')">
      <el-input v-model="dataForm.password" type="password" :placeholder="$t('updatePassword.password')"></el-input>
    </el-form-item>-->
    <!-- 短信验证码 -->
    <el-form-item prop="verifyCode" :label="$t('updatePassword.verifyCode')">
      <el-input v-model="dataForm.verifyCode" autocomplete="one-time-code" :placeholder="$t('updatePassword.verifyCode')" style="width: 20%; margin-right: 10px" />
      <el-button type="primary" :disabled="!!countdown" @click="getCheckCode(user.username)">
        {{ countdown ? `${countdown}s` : sendMsg }}
      </el-button>
    </el-form-item>
    <el-form-item prop="newPassword" :label="$t('updatePassword.newPassword')">
      <el-input v-model="dataForm.newPassword" type="password" autocomplete="one-time-code"
                :placeholder="$t('updatePassword.newPassword')" show-password style="width: 20%; margin-right: 10px" />
    </el-form-item>
    <el-form-item prop="confirmPassword" :label="$t('updatePassword.confirmPassword')">
      <el-input v-model="dataForm.confirmPassword" type="password" autocomplete="one-time-code"
                :placeholder="$t('updatePassword.confirmPassword')" show-password style="width: 20%; margin-right: 10px" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="dataFormSubmitHandle">{{ $t("confirm") }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { useAppStore } from "@/store";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";

/* ---------- 基础准备 ---------- */
const { t } = useI18n();
const router = useRouter();
const store = useAppStore();
const user = computed(() => store.state.user); // 手机号 = username

/* ---------- 表单 ---------- */
const dataFormRef = ref();
const dataForm = reactive({
  verifyCode: "",
  newPassword: "",
  confirmPassword: ""
});

/* ---------- 倒计时 ---------- */
const countdown = ref(0);
const sendMsg = ref("获取验证码");
let timer: number | null = null;

function settime() {
  countdown.value = 60;
  timer = window.setInterval(() => {
    if (countdown.value > 0) countdown.value--;
    else timer && clearInterval(timer);
  }, 1000);
}

/* ---------- 滑块+发送验证码 ---------- */
interface SlideCb {
  phone: string;
  countdown: () => void;
  success: (msg: string) => void;
  error: (msg: string) => void;
}

function slideCheck(data: SlideCb) {
  const validPhone = (p: string) => /^1[3-9]\d{9}$/.test(p);
  if (!validPhone(data.phone)) {
    data.error("请检查手机号");
    return;
  }
  // 直接取全局 TencentCaptcha
  const captcha = new (window as any).TencentCaptcha("194163642", (res: any) => {
    if (res.ret === 0) {
      baseService
        .post("/h5/testDescribeCaptchaResult", {
          randstr: res.randstr,
          ticket: res.ticket,
          phone: data.phone
        })
        .then((apiRes: any) => {
          if (apiRes.code === 0 && apiRes.CaptchaCode === "1") {
            data.countdown();
            data.success("发送验证码成功");
          } else {
            data.error("验证失败");
          }
        })
        .catch((e) => {
          data.error(e);
          console.log(e);
        });
    }
  });
  captcha.show();
}

function getCheckCode(phone: string) {
  if (countdown.value) return;
  slideCheck({
    phone,
    countdown: settime,
    success: (msg) => ElMessage.success(msg),
    error: (msg) => ElMessage.error(msg)
  });
}

/* ---------- 校验规则 ---------- */
const validateConfirmPassword = (rule: any, value: string, callback: (e?: Error) => void) => {
  if (dataForm.newPassword !== value) {
    callback(new Error(t("updatePassword.validate.confirmPassword")));
  } else {
    callback();
  }
};

const rules = ref({
  verifyCode: [{ required: true, message: "请输入短信验证码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: (e?: Error) => void) => {
        if (value.length < 8) return callback(new Error("密码长度不能小于8位"));
        let hasUpper = false,
          hasLower = false,
          hasNum = false;
        for (const ch of value) {
          if (ch >= "A" && ch <= "Z") hasUpper = true;
          else if (ch >= "a" && ch <= "z") hasLower = true;
          else if (ch >= "0" && ch <= "9") hasNum = true;
        }
        if (!hasUpper) return callback(new Error("密码需要包含大写字母"));
        if (!hasLower) return callback(new Error("密码需要包含小写字母"));
        if (!hasNum) return callback(new Error("密码需要包含数字"));
        callback();
      },
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: t("validate.required"), trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" }
  ]
});

/* ---------- 提交 ---------- */
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) return;

    // 与后台保持一致字段名
    const params: IObject = {
      newPassword: dataForm.newPassword,
      checkCode: dataForm.verifyCode
    };

    baseService
      .get("sys/user/password", params)
      .then((res: any) => {
        if (res.code === 0) {
          ElMessage.success("密码修改成功");
          setTimeout(() => router.replace("/login"), 500);
        } else {
          ElMessage.error(res.msg || "验证码错误");
        }
      });
  });
};
</script>
